package com.mlizhi.modules.login;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mlizhi.base.MlzApplication;
import com.mlizhi.base.NetWorkManager;
import com.mlizhi.base.SecurityUtil;
import com.mlizhi.base.Session;
import com.mlizhi.kingdom.R;
import com.mlizhi.modules.spec.SpecActivity;
import com.mlizhi.modules.spec.util.JsonUtil;
import com.mlizhi.utils.Constants;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;

/**
 * handset devices, settings are presented as a single list. On tablets,
 * settings are split by category, with category headers shown to the left of
 * the list of settings.
 * <p>
 * See <a href="http://developer.android.com/design/patterns/settings.html">
 * Android Design: Settings</a> for design guidelines and the <a
 * href="http://developer.android.com/guide/topics/ui/settings.html">Settings
 * API Guide</a> for more information on developing a Settings UI.
 */
public class Regist2Activity extends Activity {

	private Session mSession;
	private MlzApplication mlzApplication;
	private EditText userNameEditText,passwordEditText,rePasswordEditText;
	private Context mContext;
	private String userName = "";
	private String password = "";
	private String repassword = "";
	private RequestQueue mRequestQueue;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_login_regist2);
		mlzApplication = (MlzApplication) getApplication();
		mSession = Session.get(getApplicationContext());
		/** 发送策略定义了用户由统计分析SDK产生的数据发送回友盟服务器的频率。 */
		MobclickAgent.updateOnlineConfig( mContext );
		/** 设置是否对日志信息进行加密, 默认false(不加密). */
		AnalyticsConfig.enableEncrypt(true);
		userNameEditText = (EditText) findViewById(R.id.user_info_username);
		passwordEditText = (EditText) findViewById(R.id.user_info_password);
		rePasswordEditText = (EditText) findViewById(R.id.user_info_repassword);
		
	}

	public void onRegistClick(View view) {
		switch (view.getId()) {
		case R.id.regist_password2_back:
			finish();
			break;
		case R.id.regist2_submit_btn:
			submitRegist();
			break;
		default:
			break;
		}
	}
	 

	/**
	 * 提交注册
	 */
	private void submitRegist() {
        userName = userNameEditText.getText().toString();
        password = passwordEditText.getText().toString();
        repassword = rePasswordEditText.getText().toString();
        if("".equals(userName) || userName == null) {
        	Toast.makeText(mContext, "用户名为空！", Toast.LENGTH_SHORT).show();
        	return;
        }
        
        if("".equals(password) || password == null) {
        	Toast.makeText(mContext, "密码为空！", Toast.LENGTH_SHORT).show();
        	return;
        }
        
        if(password.equals(repassword)) {
            boolean netUsable = NetWorkManager.getNewInstance().isNetworkConnected(mContext);
            if (netUsable) {
                mRequestQueue = Volley.newRequestQueue(getApplicationContext());
                // Request a string response from the provided URL.
                StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_USER_REGIST_URL,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                String code = JsonUtil.getHeaderCode(response);
                                if(Constants.RESULT_JSON_HEADER_CODE_SUCCESS.equals(code)){
                                	mSession.setUserName(userName);                                	
                                	try {
                                		JSONObject customerObj = JsonUtil.getBodyJsonObject(response).getJSONObject("customer");
										mSession.setUid(customerObj.getString("id"));
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
                                	
                                	Regist2Activity.this.startActivity(new Intent(Regist2Activity.this,SpecActivity.class));
                        			Regist2Activity.this.finish();
                        			mlzApplication.removeActivities();
                                }else {
                                    Toast.makeText(mContext,JsonUtil.getHeaderErrorInfo(response),Toast.LENGTH_SHORT).show();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(mContext,error.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        String timestamp = SecurityUtil.getTimestamp();
                        Map<String, String>  params = new HashMap<String, String>();
                        params.put("mobile",  mSession.getAccount());
                        params.put("nikeName",  userName);
                        params.put("password",  password);
                        params.put("companyId",  Constants.COMPANY_ID);
                        params.put("sex",  mSession.getUserSex());
                        params.put("birthday",  mSession.getUserBriday());
                        params.put(Constants.URL_TIMESTAMP,timestamp );
                        params.put(Constants.URL_KEY,SecurityUtil.getMd5String(timestamp));
                        return params;
                    }
                };
//                stringRequest.setTag(TAG);
                mRequestQueue.add(stringRequest);
                mRequestQueue.start();
            }else {
                Toast.makeText(mContext,R.string.net_connected_failure,Toast.LENGTH_SHORT).show();
            }
        }else{
        	Toast.makeText(mContext, "两次密码不一致！", Toast.LENGTH_SHORT).show();
        }
    }

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("SplashScreen"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写)
	    MobclickAgent.onResume(this);          //统计时长
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("SplashScreen"); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息 
		MobclickAgent.onPause(this);
	}
	
   
}